#pragma region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#pragma endregion

#pragma once

class ROTRegister
{
private:
	DWORD _dwRegister;
	bool _autoRevoke;

public:
	ROTRegister(bool autoRevoke = true) : _dwRegister(0), _autoRevoke(autoRevoke)
	{
	}

	virtual ~ROTRegister()
	{
		if(_dwRegister != 0 && _autoRevoke)
			Revoke();
	}

	HRESULT Register(IUnknown* unk)
	{
		IRunningObjectTable *pROT;
		if(FAILED(GetRunningObjectTable(0, &pROT)))
			return E_FAIL;

		IMoniker* pMoniker = NULL;
		HRESULT hr = CreateMoniker(unk, &pMoniker);
		if(SUCCEEDED(hr))
		{
			hr = pROT->Register(/*ROTFLAGS_ALLOWANYCLIENT |*/ ROTFLAGS_REGISTRATIONKEEPSALIVE, unk, pMoniker, &_dwRegister);
			pMoniker->Release();
		}
		ATLTRACE_TS(atlTraceGeneral, TraceLevel::Info,
			"ROTRegister::Register() : graph has been registered in ROT id=%d - 0x%08X.\r\n", _dwRegister, hr);

		pROT->Release();
		return hr;
	}

	bool IsRegistered()
	{
		return _dwRegister != 0;
	}
	

	HRESULT IsRegistered(IUnknown* unk)
	{
		IRunningObjectTable* pROT;
		if(FAILED(GetRunningObjectTable(0, &pROT)))
			return E_FAIL;

		IMoniker* pMoniker = NULL;
		HRESULT hr = CreateMoniker(unk, &pMoniker);
		if(SUCCEEDED(hr))
		{
			hr = pROT->IsRunning(pMoniker);
			pMoniker->Release();
		}

		pROT->Release();
		return hr;
	}

	void Revoke()
	{
		IRunningObjectTable *pROT;
		if(SUCCEEDED(GetRunningObjectTable(0, &pROT)))
		{
			pROT->Revoke(_dwRegister);
			pROT->Release();
			_dwRegister = 0;
		}
	}

	virtual HRESULT CreateMoniker(IUnknown* unk, IMoniker** pMoniker) = 0;
};


/// <summary>
/// GraphEdit can load a filter graph created by an external process. With this feature, you can see exactly
/// what filter graph your application builds, with only a minimal amount of additional code in your application.
/// This feature requires Windows 2000, Windows XP, or later.
/// WARNING!!!
/// Starting in Windows Vista, you must register proppage.dll to enable this feature. Proppage.dll is included in the Windows SDK.
/// </summary>
class GraphBulderROTRegister : public ROTRegister
{
public:
	GraphBulderROTRegister(bool autoRevoke = true) : ROTRegister(autoRevoke)
	{
	}

	virtual HRESULT CreateMoniker(IUnknown* unk, IMoniker** pMoniker)
	{
		WCHAR wsz[256];
		wsprintfW(wsz, L"FilterGraph %08x pid %08x", (DWORD_PTR)unk, GetCurrentProcessId());
		return CreateItemMoniker(L"!", wsz, pMoniker);
	}
};



